package com.jason.lucene.example.index;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.core.SimpleAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.FieldType;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexOptions;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.RAMDirectory;
import org.junit.Before;

import java.nio.file.Paths;

/**
 * @author he peng
 * @create 2017/11/30 11:24
 * @see
 */
public class BaseIndexingTest {

    protected String[] keywords = {"1" , "2"};
    protected String[] unindexed = {"Netherlands" , "Italy"};
    protected String[] unstored = {"Amsterdam has lots if bridges" , "Venice has lots of canals"};
    protected String[] text = {"Amsterdam" , "Venice"};
    protected Directory indexDir;


    @Before
    public void setUp() throws Exception {
        this.indexDir = FSDirectory.open(Paths.get("C://lucene//index"));
//        this.indexDir = new RAMDirectory();
        addDocument(this.indexDir);
    }

    protected void addDocument(Directory indexDir) throws Exception {
        IndexWriterConfig conf = new IndexWriterConfig(getAnalyzer());
        conf.setUseCompoundFile(true);
        IndexWriter indexWriter = new IndexWriter(indexDir, conf);
        FieldType unIndexFieldType = new FieldType();
        unIndexFieldType.setIndexOptions(IndexOptions.NONE);
        unIndexFieldType.setStored(true);
        for (int i = 0 ; i < this.keywords.length ; i++ ) {
            Document doc = new Document();
            doc.add(new Field("id" , this.keywords[i] , TextField.TYPE_STORED));
            doc.add(new Field("country" , this.unindexed[i] , unIndexFieldType));
            doc.add(new Field("contents" , this.unstored[i] , TextField.TYPE_NOT_STORED));
            doc.add(new Field("city" , this.text[i] , TextField.TYPE_STORED));
            System.out.println("add document : " + doc);
            indexWriter.addDocument(doc);
        }
        indexWriter.close();
    }

    protected Analyzer getAnalyzer() {
        return new SimpleAnalyzer();
    }
}
